var vm = new Vue({
    el: '#app',
    data: function(){
        return {
            socket: null,
            isLogin: true,
            loginDialogVisible: false,
            groups: [{avatar: "//cdn.v2ex.com/gravatar?d=mm", name: "bottle", _id:"5adacd"},{avatar: "//cdn.v2ex.com/gravatar?d=mm", name: "bottle2", _id:"5adace"}],
            messages: {"5adacd":[],"5adace":[]},
            currentGroup: {avatar: "//cdn.v2ex.com/gravatar?d=mm", name: "bottle", _id:"5adacd"},
            loginUsername: "",
            loginPassword: "",
            userId: ""
        }
    },
    methods: {
        ws : function() {
            var _this = this;
            if (!window.WebSocket) {
                window.WebSocket = window.MozWebSocket;
            }
            if (window.WebSocket) {
                this.socket = new WebSocket("ws://localhost:8091/ws");
                this.socket.onopen = function(){

                }
                this.socket.onmessage = function(event){
                    let obj = JSON.parse(event.data);
                    let createTime = new Date(obj.createTime).getHours() + ':' +new Date(obj.createTime).getMinutes();
                    let isSelf = obj.user["_id"] === "bottle_self";
                    let object = { avatar: obj.user.avatar, name:obj.user.username,content:obj.content,createTime:createTime,isSelf: isSelf };
                    _this.messages["5adacd"].push(object);
                }
                this.socket.onclose = function(e){
                    console.log("close");
                }
                this.socket.onerror = function(e){
                    console.log(e);
                }
            } else {
                alert("你的浏览器不支持WebSocket。请不要使用低版本的IE浏览器。");
            }
        },
        sendMsg(content) {
            let contentObj = {content:content, type:"text", to: this.currentGroup._id};
            this.socket.send(JSON.stringify(contentObj))
        },
        load : function () {
            this.ws()
        },
        login(){
            $.ajax({
                url: "/api/login?userId=" + this.loginUsername,
                success: function (result) {
                    this.isLogin = true;
                    this.userId = result;
                }
            })
        }
    },
    created: function() {
        this.load()
    }
})
